package com.ubxtech.web.locale;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.ubxtech.core.context.ContextConstants;
import com.ubxtech.core.context.ContextUtil;
import com.ubxtech.web.properties.AuthProperties;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author Victor.Xiao
 * @since 2023-09-15 11:46
 **/
public class CustomLocaleDateSerializer extends JsonSerializer<Date> {

    private AuthProperties authProperties;
    public CustomLocaleDateSerializer(AuthProperties authProperties) {
        this.authProperties = authProperties;
    }
    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        try {
            TimeZone timeZone = TimeZone.getDefault();
            if (ContextUtil.get(ContextConstants.HEADER_TIME_ZONE_ID)!=null && StrUtil.isNotBlank(ContextUtil.get(ContextConstants.HEADER_TIME_ZONE_ID).toString())) {
                timeZone = TimeZone.getTimeZone(ZoneId.of(ContextUtil.get(ContextConstants.HEADER_TIME_ZONE_ID).toString()));
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(authProperties.getTimeFormat());
            simpleDateFormat.setTimeZone(timeZone);
            String format = simpleDateFormat.format(date);
            // 输处结果，这里注意“writeString”表示写出json的格式。写出的可以是多种格式，自己看具体方法
            jsonGenerator.writeString(format);
        } catch (Exception e) {
            jsonGenerator.writeString("error format date");
        }
    }
}